package service;

import mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import po.Result;
import po.User;

import javax.servlet.http.HttpSession;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public String login(User user, HttpSession session) throws Exception {
        User foundUser = userMapper.findUserByNumber(user.getNumber());
        if(foundUser != null) {
            if(foundUser.getPassword().equals(user.getPassword())) {
                session.setAttribute("userName", foundUser.getName());
                session.setAttribute("userNumber", foundUser.getNumber());
                return "index";
            }
            return "error";
        }
        return "null";
    }

    @Override
    public Result updatePwd(String number, String oldPwd, String newPwd) throws Exception {
        Result result = new Result();
        User user = userMapper.findUserByNumber(number);
        if (oldPwd.equals(user.getPassword())) {
            try {
                user.setPassword(newPwd);
                userMapper.updatePwdByNumber(user);
            } catch (Exception e) {
                result.setResult("fail");
                result.setMessage("修改失败！");
                return result;
            }
            result.setResult("success");
            result.setMessage("修改成功！");
            return result;
        }
        result.setResult("fail");
        result.setMessage("旧密码错误！");
        return result;
    }
}
